﻿<%@ Page Language="C#" MasterPageFile="~/SIPO.master" AutoEventWireup="true" CodeFile="recImpositionUploadform.aspx.cs"
    Inherits="SIPO.Web.Forms.Administration.recImpositionUploadform" %>

<asp:Content ID="ctnBody" ContentPlaceHolderID="body" runat="server">
    <link type="text/css" rel="stylesheet" href="<%= ResolveUrl("~/styles/ui.jqgrid.css") %>" />
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.wrapper.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.fileupload.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.iframe-transport.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.inputmask.bundle.min.js") %>" type="text/javascript"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
    <script src="<%= ResolveUrl("~/scripts/plupload/moxie.min.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/plupload/plupload.full.min.js") %>" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {

            $("#btnClose").button({ icons: { primary: "ui-icon-close"} });
            $("#btnSave").button({ icons: { primary: "ui-icon-disk"} });
            $("#btnCheckExcel").button({ icons: { primary: "ui-icon-edit"} });
            $("#btnExport").button({ icons: { primary: "ui-icon-extlink"} });

        });          

    </script>
    <script type="text/javascript">

        $(document).ready(function () {

            var path = '<%= ResolveUrl("~/ajaxhandler/Administration/recImpositionUploadhandler.ashx") %>';
            var method = "?method=getdataexcel";
            var methodCheckExcel = "?method=checkexcel";
            var methodSave = "?method=insert";
            var methodDownload = "?method=dowloadtemplate";
            //        var dicterror;
            var page;
            var pagesize;
            var records;
            var indexData;
            var dataGrid;

            var uploader = new plupload.Uploader({
                runtimes: 'html5,flash,silverlight',
                browse_button: 'pickfiles',
                container: 'container',
                max_file_size: '5mb',
                url: '<%= ResolveUrl("~/AjaxHandler/Administration/recImpositionUploadhandler.ashx") %>' + '?method=checkexcel',
                flash_swf_url: '<%= ResolveUrl("~/scripts/Moxie.swf") %>',
                silverlight_xap_url: '<%= ResolveUrl("~/scripts/Moxie.xap") %>',
                filters: [
			{ title: "Excel files", extensions: "xls,xlsx" }
		],
                resize: { width: 320, height: 240, quality: 90 }
            });

            uploader.bind('Init', function (up, params) {

                var msg = 'Untuk dapat melakukan proses unggah / upload dokumen, browser anda harus mendukung salah satu teknologi, HTML 5 / Flash / Silverlight';

                if (params.runtime == 'html5') {
                    msg = '';
                } else if (params.runtime == 'flash') {
                    msg = '';
                } else if (params.runtime == 'silverlight') {
                    msg = ''
                }

                if (msg != '') {
                    alert(msg);
                }

            });

            uploader.init();

            uploader.bind('FilesAdded', function (up, files) {

                if (up.files.length > 1) {
                    alert('Hanya diperbolehkan satu file untuk di upload!');
                    return false;
                }

                $.each(files, function (i, file) {
                    $('#filelist').append(
                        '<div id="' + file.id + '">' +
                file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' + '</div>');
                });

                up.refresh(); // Reposition Flash/Silverlight
            });

            uploader.bind('Error', function (up, err) {
                $('#filelist').append("<div>Error: " + err.code +
			", Message: " + err.message + (err.file ? ", File: " + err.file.name : "") + "</div>");

                up.refresh(); // Reposition Flash/Silverlight

            });

            function showloading() {
                $('#siteLoader').show();
            }

            function hideloading() {
                $('#siteLoader').hide();
            }

            function LoadGrid() {
                showloading();
                var pathUrl = path + method;
                $('#ExcelGridView').jqGrid('GridUnload');
                $.ajax({
                    type: 'POST',
                    url: pathUrl,
                    dataType: 'json',
                    success: function (data) {
                        isSuccess = data.isSuccess;
                        if (!isSuccess) {
                            $("#btnSave").attr('disabled', 'disabled');
                            alert(data.errorMessage);
                            //return;
                        }
                        else { $("#btnSave").removeAttr('disabled'); }
                        dataGrid = data;
                        var sort = data.grid.SortName;
                        var models = [];
                        models = data.grid.ColModel;
                        var msgError = data.errorMessage;
                        $('#<%= ErrorMessageTextBox.ClientID %>').val(msgError);
                        hideloading();
                        $('#ExcelGridView').jqGrid({
                            url: pathUrl,
                            datatype: 'json',
                            colModel: models,
                            rowNum: 10,
                            multiselect: true,
                            rowList: [5, 10, 15, 20],
                            pager: '#PagerExcelGridView',
                            sortname: sort,
                            sortorder: 'asc',
                            viewrecords: true,
                            shrinkToFit: false,
                            jsonReader: { repeatitems: false },
                            width: $(document).width() - 60,
                            height: 'auto',
                            caption: 'Hasil Upload',
                            ajaxGridOptions: { cache: false },
                            gridComplete: function () {
                                var rowData = $("#ExcelGridView").getDataIDs();
                                for (var i = 0; i < rowData.length; i++) {
                                    var rowData2 = jQuery("#ExcelGridView").jqGrid('getRowData', rowData[i]);
                                    var iserror = rowData2['IsError'].toString();
                                    if (iserror == 'Not Valid')
                                        $("#ExcelGridView").jqGrid('setRowData', rowData[i], false, { background: 'aqua' });
                                }
                                $("#ExcelGridView").jqGrid('hideCol', ["IsError"]);
                                    var colModels = jQuery("#ExcelGridView").jqGrid('getGridParam', 'colModel');
                                    for (i = 1; i < colModels.length; i++) {
                                        var colModel = colModels[i];
                                        var colData = jQuery("#ExcelGridView").jqGrid('getCol', colModel.name, false);
                                        for (j = 0; j < colData.length; j++) {
                                            if (colData[j] != 0) {
                                                //alert(j + ' GridName_' + colModel.name)

                                            }
                                        }
                                    }
                            }
                            //                            loadComplete: function (data) {
                            //                                //                            console.log(data);
                            //                                var responseText = $.parseJSON(data.responseText);
                            //                                //                            console.log(responseText);
                            //                                var dictError = responseText.dictError;

                            //                                page = parseInt(responseText.page);
                            //                                pagesize = parseInt(responseText.pagesize);
                            //                                records = parseInt(responseText.records);

                            //                                var pagedisplay = (page * pagesize);
                            //                                var jumlah = pagedisplay - pagesize;
                            //                                pagedisplay = records > pagedisplay ? pagedisplay : records;
                            //                                var total = pagedisplay == 0 ? 0 : pagedisplay;
                            //                                var rowid = 1;
                            //                                //                            alert(total);
                            //                                //                            alert(jumlah);
                            //                                for (counter = jumlah; counter < total; counter++) {
                            //                                    var dataErrorIndex = dictError[counter];
                            //                                    var odataErrorIndex = JSON.stringify(dataErrorIndex);
                            //                                    //                                if (total == 21) {
                            //                                    //                                    alert(rowid);
                            //                                    //                                    alert(counter);
                            //                                    //                                }
                            //                                    if (odataErrorIndex != undefined) {
                            //                                        for (counter2 = 0; counter2 < odataErrorIndex.length; counter2++) {
                            //                                            var dataErrorIndex2 = dataErrorIndex[counter2];
                            //                                            //                                    if (counter == 20) {
                            //                                            //                                        rowid = 1;
                            //                                            //                                    }
                            //                                            //                                    console.log(dataErrorIndex2);
                            //                                            $("#ExcelGridView").setCell(rowid, dataErrorIndex2, '', { 'color': 'red' });
                            //                                            var value = $("#ExcelGridView").getCell(rowid, dataErrorIndex2);
                            //                                            if (value == '' || value == 'undefined' || value == null) {
                            //                                                $("#ExcelGridView").setCell(rowid, dataErrorIndex2, '', { 'background': 'red' });
                            //                                            }
                            //                                        }
                            //                                    }
                            //                                    //                                console.log(dataErrorIndex);
                            //                                    //                                $.each(dataErrorIndex, function(k, v) {
                            //                                    //                                    $("#ExcelGridView").setCell(rowid, v, '', { 'color': 'red' });
                            //                                    //                                    var value = $("#ExcelGridView").getCell(rowid, v);
                            //                                    //                                    if (value == '' || value == 'undefined' || value == null) {
                            //                                    //                                        $("#ExcelGridView").setCell(rowid, v, '', { 'background': 'red' });
                            //                                    //                                    }
                            //                                    //                                });
                            //                                    rowid++;
                            //                                }
                            //                                //                            console.log(responseText.rows);

                            //                                //                            $.each(dictError, function(index) {
                            //                                //                                //                                console.log(dataErrorIndex);
                            //                                //                                var x = parseInt(index) + 1;
                            //                                //                                var dataErrorIndex = dictError[index];
                            //                                //                                //                                if (rowid == x) {
                            //                                //                                $.each(dataErrorIndex, function(k, v) {
                            //                                //                                    $("#ExcelGridView").setCell(x, v, '', { 'color': 'red' });
                            //                                //                                    var value = $("#ExcelGridView").getCell(x, v);
                            //                                //                                    if (value == '' || value == 'undefined' || value == null) {
                            //                                //                                        $("#ExcelGridView").setCell(x, v, '', { 'background': 'red' });
                            //                                //                                    }
                            //                                //                                });
                            //                                //                                //                                }
                            //                                //                            });
                            //                            }
                            //                        ,
                            //                        afterInsertRow: function(rowid) {
                            //                            var dictError = data.dictError;
                            //                            $.each(dictError, function(index) {
                            //                                var dataErrorIndex = dictError[index];
                            //                                var x = parseInt(index) + 1;
                            //                                if (rowid == x) {
                            //                                    $.each(dataErrorIndex, function(k, v) {
                            //                                        $("#ExcelGridView").setCell(x, v, '', { 'color': 'red' });
                            //                                        var value = $("#ExcelGridView").getCell(x, v);
                            //                                        if (value == '' || value == 'undefined' || value == null) {
                            //                                            $("#ExcelGridView").setCell(x, v, '', { 'background': 'red' });
                            //                                        }
                            //                                    });
                            //                                }
                            //                            });
                            //                        }
                        });
                    },
                    error: function () {
                        alert('error');
                    }
                });
            }

            $("#btnSave").click(function () {
                //CallAjax(path, methodSave);
                //return false;
                //return false;
                var grid = $('#ExcelGridView');
                var selIds = grid.jqGrid('getGridParam', 'selarrrow'),
                selTextDebtorCode = [];
                $.each(selIds, function () {
                    selTextDebtorCode.push(grid.jqGrid('getCell', this, 'DebtorCode'));
                });
                if (selTextDebtorCode.length == 0)
                    alert('Pilih data yang akan di upload !');
                else {
                    showloading();
                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Administration/recImpositionUploadhandler.ashx") %>';
                    $.ajax({
                        type: 'POST',
                        url: handlerUrl + "?method=insert&debtorcode=" + selTextDebtorCode + "",
                        contentType: 'application/json',
                        dataType: 'json',
                        data: '',
                        success: function (data) {
                            if (data.IsSuccess) {
                                $("#btnSave").attr('disabled', 'disabled');
                                alert(data.Message);
                            }
                            else {
                                alert(data.Message);
                            }
                            hideloading();
                        },
                        error: function (response) {
                            var r = JSON.parse(response.responseText);
                            alert("Error Message: " + r.Message);
                        }
                    });
                }
            });

            $("#btnExport").click(function () {
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Administration/recImpositionUploadhandler.ashx?method=dowloadtemplate") %>';
                window.open(handlerUrl);
                $("#btnExport").attr('disabled', 'disabled');

            });

            $("#btnCheckExcel").click(function () {
                if (uploader.files.length > 0) // Insert with uploaded file.
                {
                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Administration/recImpositionUploadhandler.ashx") %>';
                    uploader.settings.url = handlerUrl + '?method=checkexcel';
                    uploader.start();

                    var session = '<%= Session["DataUpload"] %>';
                    //alert(session);
                    if (session != null)
                        LoadGrid();
                }
            });

        });

    </script>
    <style type="text/css">
        .style1
        {
            width: 8px;
        }
        .style2
        {
            width: 165px;
        }
    </style>
    <div>
        <table border="0">
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
                <td>
                    <div style="text-align: right; padding-top: 10px;">
                        <button id="btnExport" type="button">
                            Download Template</button>
                    </div>
                </td>
            </tr>
        </table>
        <table border="0">
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Lampiran
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <div id="container">
                        <a id="pickfiles" class="plupload_button plupload_add ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary"
                            href="#"><span class="ui-button-icon-primary ui-icon ui-icon-circle-plus" /><span
                                class="ui-button-text">Add Files</span> </a>
                        <br />
                        <div id="filelist">
                        </div>
                    </div>
                </td>
                <td>
                </td>
                <td>
                </td>
                <td>
                </td>
                <td>
                    <button id="btnCheckExcel" type="button">
                        Cek Excel</button>
                </td>
            </tr>
        </table>
        <br />
        <table border="0">
            <tr>
                <td colspan="2">
                    <table id="ExcelGridView" class="scroll" cellpadding="0" cellspacing="0">
                    </table>
                    <div id="PagerExcelGridView" class="scroll">
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
        </table>
        <table>
            <tr>
                <td>
                    <div id="siteLoader" style="display: none; text-align: center;">
                        <div id="siteDetailLoader">
                            <img src="../../images/loading_anchor.gif" border="0" alt="cargando" />
                        </div>
                    </div>
                </td>
            </tr>
        </table>
        <table border="0">
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
                <td>
                    <div style="text-align: right; padding-top: 10px;">
                        <button id="btnSave" type="button">
                            Simpan</button>
                        <button id="btnClose" type="reset">
                            Batal</button>
                    </div>
                </td>
            </tr>
        </table>
        <fieldset style="width: 600px !important;">
            <legend>Remarks</legend>
            <asp:TextBox ID="ErrorMessageTextBox" Style="font: 11px Arial,Helvetica,sans-serif !important;"
                TextMode="MultiLine" Rows="6" runat="server" Width="500"></asp:TextBox></fieldset>
    </div>
</asp:Content>
